package com.msb.mall.ware.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.msb.common.constant.WareConstant;
import com.msb.common.utils.PageUtils;
import com.msb.common.utils.Query;
import com.msb.mall.ware.dao.PurchaseDao;
import com.msb.mall.ware.entity.PurchaseDetailEntity;
import com.msb.mall.ware.entity.PurchaseEntity;
import com.msb.mall.ware.service.PurchaseDetailService;
import com.msb.mall.ware.service.PurchaseService;
import com.msb.mall.ware.service.WareSkuService;
import com.msb.mall.ware.vo.PurchaseFinishVo;
import com.msb.mall.ware.vo.PurchaseItemFinishVo;
import com.msb.mall.ware.vo.PurchaseMergeVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    PurchaseDetailService purchaseDetailService;
    @Autowired
    WareSkuService wareSkuService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if(StringUtils.isNotEmpty(key)){
            wrapper.and((w) ->{
                w.eq("id",key).or().like("assignee_name",key)
                        .or().like("phone",key);
            });

        }
        String status = (String) params.get("status");
        if(StringUtils.isNotEmpty(status)){
            wrapper.eq("status",status);
        }
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    @Override
    public List<PurchaseEntity> unReceiveList(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("status",0).or().eq("status",1);
        String assigneeName = (String) params.get("assigneeName");
        if(StringUtils.isNotEmpty(assigneeName)){
            wrapper.like("assignee_name",assigneeName);
        }
        return this.list(wrapper);
    }

    /**
     * 完成采购需求的合单
     * @param purchaseMergeVo 参数
     * @return null
     */

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer merge(PurchaseMergeVo purchaseMergeVo) {
        if(purchaseMergeVo.getPurchaseId() == null){
            //新建采购单
            PurchaseEntity purchase = new PurchaseEntity();
            purchase.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchase.setCreateTime(new Date());
            purchase.setUpdateTime(new Date());
            this.save(purchase);
            purchaseMergeVo.setPurchaseId(purchase.getId());
        }
        //判断采购单的状态，只能是新建或已分配 已领取酒不能在合单了
        PurchaseEntity purchaseEntity = this.getById(purchaseMergeVo.getPurchaseId());
        if(purchaseEntity.getStatus() >= WareConstant.PurchaseStatusEnum.RECEIVE.getCode()){
            //该菜单不能合单
            return -1;
        }
        //整合采购单
        List<PurchaseDetailEntity> collect = purchaseMergeVo.getItems().stream().map(i -> {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            detailEntity.setId(i);
            detailEntity.setPurchaseId(purchaseMergeVo.getPurchaseId());
            detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGED.getCode());
            return detailEntity;
        }).filter(id ->{
            PurchaseDetailEntity item = purchaseDetailService.getById(id);
            return item.getStatus() == WareConstant.PurchaseDetailStatusEnum.CREATED.getCode()
                    || item.getStatus() == WareConstant.PurchaseDetailStatusEnum.ASSIGED.getCode();
        }).collect(Collectors.toList());
        if(!collect.isEmpty()){
            purchaseDetailService.updateBatchById(collect);
        }
        //更新对应的采购单的更新时间
        PurchaseEntity entity = new PurchaseEntity();
        entity.setUpdateTime(new Date());
        entity.setId(purchaseMergeVo.getPurchaseId());
        this.updateById(entity);
        return 1;
    }

    /**
     * 领取采购单
     * @param ids [2,3,4]
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void receive(List<Long> ids) {
        //1.领取的采购但只能是新建或者已分配 其他不能领取
        List<PurchaseEntity> list = ids.stream().map(this::getById)
                .filter(item -> item.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() ||
                item.getStatus() == WareConstant.PurchaseDetailStatusEnum.ASSIGED.getCode()).peek(item ->{
            item.setUpdateTime(new Date());
            item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
        }).collect(Collectors.toList());
        //2.更新采购单已领取
        this.updateBatchById(list);
        //3.更新采购项的状态欸 正在采购
        for (Long id : ids) {
          List<PurchaseDetailEntity> details = purchaseDetailService.listDetailByPurchaseId(id);
            List<PurchaseDetailEntity> collect = details.stream().map(item -> {
                PurchaseDetailEntity entity = new PurchaseDetailEntity();
                entity.setId(item.getId());
                entity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return entity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(collect);
        }
    }

    /**
     * 完成采购
     * @param finishVo 参数
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void finish(PurchaseFinishVo finishVo) {
        //获取采购单编号
        Long id = finishVo.getId();
        //2.改变采购项的状态
        //记录采购的状态为完成
        boolean flag = true;
        //获取所有的采购项
        List<PurchaseItemFinishVo> items = finishVo.getItems();
        List<PurchaseDetailEntity> finishList = new ArrayList<>();
        for (PurchaseItemFinishVo finish :items) {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            if(finish.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()){
                //记录采购项出现问题
                flag = false;
                detailEntity.setStatus(finish.getStatus());
            }else{
                //采购项采购成功
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                //3.将采购成功的采购项进行入库操作
                //采购项编号 查询对应的采购项详情
                PurchaseDetailEntity detailEntity1 = purchaseDetailService.getById(finish.getItemId());
                wareSkuService.addStock(detailEntity1.getSkuId(),detailEntity1.getWareId(),detailEntity1.getSkuNum());
            }
            detailEntity.setId(finish.getItemId());
            finishList.add(detailEntity);
        }
        //批量更新采购项
        purchaseDetailService.updateBatchById(finishList);

        //1.改变采购单的状态
        PurchaseEntity purchase = new PurchaseEntity();
        purchase.setId(id);
        purchase.setStatus(flag ? WareConstant.PurchaseStatusEnum.FINISH.getCode() : WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode());
        purchase.setUpdateTime(new Date());
        this.updateById(purchase);
    }

}
